package com.xcity;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.xcity.config.ConfigLoader;
import com.xcity.game.account.AccountService;
import com.xcity.game.achievement.AchievementService;
import com.xcity.game.achievement.AchievementTemplate;
import com.xcity.game.activity.charm.CharmTopActivityService;
import com.xcity.game.activity.chips.ChipsCollectActivityService;
import com.xcity.game.activity.cumulativerecharge.CumulativeRechargeActivityService;
import com.xcity.game.activity.cumulativerecharge.CumulativeRechargeTemplate;
import com.xcity.game.activity.exchange.ExchangeActivityService;
import com.xcity.game.activity.exchange.ItemExchangeTemplate;
import com.xcity.game.activity.gift.GiftExchangeActivityService;
import com.xcity.game.activity.invite.InviteActivityService;
import com.xcity.game.activity.limitbuy.DailyLimitBuyActivityService;
import com.xcity.game.activity.login.DailyLoginActivityService;
import com.xcity.game.activity.login.DailyLoginRewardTemplate;
import com.xcity.game.activity.luckdraw.BigLuckDrawActivityService;
import com.xcity.game.activity.luckdraw.BigLuckDrawTemplate;
import com.xcity.game.activity.mooncard.MoonCardActivityService;
import com.xcity.game.activity.newplayer.ActivityNewPlayerService;
import com.xcity.game.activity.newplayer.NewPlayerShopTemplate;
import com.xcity.game.activity.newplayer.NewPlayerTaskTemplate;
import com.xcity.game.activity.newplayer.NewPlayerViewTemplate;
import com.xcity.game.activity.recharge.FirstRechargeService;
import com.xcity.game.activity.recharge.RechargeGiftActivityService;
import com.xcity.game.activity.redpacket.RedPacketActivityService;
import com.xcity.game.activity.sevendays.SevenDaysSignInActivityService;
import com.xcity.game.activity.sevendays.SevenDaysSignInTemplate;
import com.xcity.game.activity.str.StrengthMealActivityService;
import com.xcity.game.activity.surprise7days.Surprise7DaysActivityService;
import com.xcity.game.activity.surprise7days.Surprise7DaysTemplate;
import com.xcity.game.activity.thirtyday.ThirtyDayRechargeTemplate;
import com.xcity.game.activity.thirtyday.ThirtyDayRewardTemplate;
import com.xcity.game.activity.thirtyday.ThirtyDayShopTemplate;
import com.xcity.game.activity.thirtyday.ThirtyDaySignActivityService;
import com.xcity.game.activity2.ActivityService2;
import com.xcity.game.activity2.circle.CircleRankRewardTemplate;
import com.xcity.game.activity2.circle.CircleRewardTemplate;
import com.xcity.game.activity2.circle.CircleShopTemplate;
import com.xcity.game.activity2.groupbuy.template.GroupBuyConfig;
import com.xcity.game.activity2.groupbuy.template.GroupBuyScoreRewardTemplate;
import com.xcity.game.activity2.groupbuy.template.GroupBuyTemplate;
import com.xcity.game.activity2.platform.PlatformGiftDispatchService;
import com.xcity.game.activity2.share.template.QQShareActivityTemplate;
import com.xcity.game.activity2.singlerecharge.template.SingleRechargeActivityTemplate;
import com.xcity.game.adventure.AdventureService;
import com.xcity.game.adventure.template.AdventureFixedProduceTemplate;
import com.xcity.game.adventure.template.AdventureTemplate;
import com.xcity.game.arena.ArenaService;
import com.xcity.game.arena.offline.ArenaDailyRewardTemplate;
import com.xcity.game.arena.online.template.ArenaOpenTimeTemplate;
import com.xcity.game.assist.AssistService;
import com.xcity.game.battle.pve.PVEService;
import com.xcity.game.battle.pve.template.DropItemToStageTemplate;
import com.xcity.game.battle.pve.template.ResStageTemplate;
import com.xcity.game.battle.pve.template.ResStageTypeTemplate;
import com.xcity.game.battle.pve.template.StageAreaTemplate;
import com.xcity.game.battle.pve.template.StagePageTemplate;
import com.xcity.game.battle.pve.template.StageTemplate;
import com.xcity.game.battle.res.ResStageService;
import com.xcity.game.buff.BuffTemplate;
import com.xcity.game.buildv2.BuildServiceV2;
import com.xcity.game.buildv2.template.BuildTemplateV2;
import com.xcity.game.buycount.BuyCountService;
import com.xcity.game.buycount.BuyCountTemplate;
import com.xcity.game.chat.ChatService;
import com.xcity.game.combat.CombatService;
import com.xcity.game.combat.CombatUtils;
import com.xcity.game.combat.template.ClazzRestrainTemplate;
import com.xcity.game.combat.template.CombatAttributeTemplate;
import com.xcity.game.combat.template.CombatPowerConfig;
import com.xcity.game.common.GameStaticConfig;
import com.xcity.game.common.MessageConst;
import com.xcity.game.conquests.ConquestsService;
import com.xcity.game.employee.EmployeeService;
import com.xcity.game.employee.template.EmployeeBlessTemplate;
import com.xcity.game.employee.template.EmployeeExpTemplateV2;
import com.xcity.game.employee.template.EmployeeProduceMoneyByQualityV2Template;
import com.xcity.game.employee.template.EmployeeProduceV2Template;
import com.xcity.game.employee.template.EmployeeQualityUpStringTemplate;
import com.xcity.game.employee.template.EmployeeQualityUpTemplate;
import com.xcity.game.employee.template.EmployeeRecruitFixedDropTemplate;
import com.xcity.game.employee.template.EmployeeRecruiteShowTemplate;
import com.xcity.game.employee.template.EmployeeStarUpTemplate;
import com.xcity.game.employee.template.EmployeeTemplate;
import com.xcity.game.equip.EquipmentService;
import com.xcity.game.equip.template.EquipAttrNumWeightTemplate;
import com.xcity.game.equip.template.EquipAttrWeightTemplate;
import com.xcity.game.equip.template.EquipBaseTemplate;
import com.xcity.game.equip.template.EquipDataTemplate;
import com.xcity.game.equip.template.EquipSuitEffectTemplate;
import com.xcity.game.financial.FinancialService;
import com.xcity.game.financial.FinancialTemplate;
import com.xcity.game.formation.FormationService;
import com.xcity.game.guild.GuildService;
import com.xcity.game.guild.template.GuildDonateTemplate;
import com.xcity.game.guild.template.GuildExpTemplate;
import com.xcity.game.http.HttpService;
import com.xcity.game.item.DropGroupTemplate;
import com.xcity.game.item.ItemService;
import com.xcity.game.item.ItemTemplate;
import com.xcity.game.land.LandBuyTemplate;
import com.xcity.game.land.LandTemplate;
import com.xcity.game.mail.MailService;
import com.xcity.game.map.MapService;
import com.xcity.game.map.template.MineTypeTemplate;
import com.xcity.game.news.NewsService;
import com.xcity.game.npc.NpcTeamTemplate;
import com.xcity.game.npc.NpcTemplate;
import com.xcity.game.partner.PartnerQQService;
import com.xcity.game.peakroad.PeakRoadService;
import com.xcity.game.peakroad.template.PeakRoadTemplate;
import com.xcity.game.pet.PetService;
import com.xcity.game.pet.template.PetSkillLevelUpTemplate;
import com.xcity.game.pet.template.PetSkillTemplate;
import com.xcity.game.pet.template.PetTemplate;
import com.xcity.game.player.PlayerService;
import com.xcity.game.player.PlayerTrainService;
import com.xcity.game.player.cache.PlayerCacheService;
import com.xcity.game.player.robot.RobotTemplate;
import com.xcity.game.player.template.DestinyTemplate;
import com.xcity.game.player.template.PlayerLevelTemplate;
import com.xcity.game.rank.RankingService;
import com.xcity.game.recharge.RechargeService;
import com.xcity.game.recharge.RechargeTemplate;
import com.xcity.game.relation.RelationService;
import com.xcity.game.shop.ShopItemTemplate;
import com.xcity.game.shop.ShopService;
import com.xcity.game.shop.mystery.MysteryShopService;
import com.xcity.game.shop.mystery.template.MysteryShopItemTemplate;
import com.xcity.game.shop.mystery.template.MysteryShopRefreshCostTemplate;
import com.xcity.game.shop.mystery.template.MysteryShopRefreshRuleTemplate;
import com.xcity.game.shop.peak.PeakShopTemplate;
import com.xcity.game.skill.SkillService;
import com.xcity.game.skill.template.SkillTemplate;
import com.xcity.game.task.TaskService;
import com.xcity.game.task.TaskTemplate;
import com.xcity.game.treasurebox.TreasureBoxService;
import com.xcity.game.treasurebox.TreasureBoxTemplate;
import com.xcity.game.vip.VipService;
import com.xcity.game.vip.VipTemplate;
import com.xcity.game.visit.VisitService;
import com.xcity.game.worldboss.WorldBossService;
import com.xcity.game.worldboss.template.WorldBossConfig;
import com.xcity.game.worldboss.template.WorldBossRankingRewardTemplate;
import com.xcity.game.worldboss.template.WorldBossTemplate;
import com.xcity.game.worldevent.WorldEventTemplate;
import com.xcity.game.worldevent.WorldEventTimeTemplate;
import com.xcity.packet.PlayerFilter;
import com.xcity.pomelo.push.msg.TipPush;
import com.xcity.util.IdUtils;
import com.xcity.util.PlatformApi;

import naga.x.App;
import naga.x.db.impl.SqlSessionFactory;
import naga.x.game.template.TemplateService;
import naga.x.game.time.TimeUpdater;
import naga.x.net.ClientSessionService;
import naga.x.net.Packet;
import naga.x.net.filter.ConnectionsFilter;
import naga.x.net.impl.pomelo.PomeloClientSessionService;
import naga.x.net.proxy.ProxyClientSessionService;
import naga.x.util.CommonUtils;
import naga.x.util.IOUtils;

public class Server implements Runnable {
	
	public static final Logger LOG = LoggerFactory.getLogger(Server.class);

	private static Server instance;
	private boolean running = true;
	public byte state;
	private static final int DEFAULT_UPDATE_TIME = 80;
	
	public static final int STATE_REGISTER_BAN_MASK = 0x1; // 禁止注册
	public static final int STATE_LOGIN_BAN_MASK = 0x2; // 禁止登录
	
	public Server() {
		instance = this;
//		state = App.getApp().getConfig().getByteValue(Config.STATE);
		state = (byte) App.getApp().getConfig().state;
	}
	
	public static void main(String[] args) throws Exception {
		// ---fastjson config begin---
		// enum use ordinal to serialize
		JSON.DEFAULT_GENERATE_FEATURE = SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.WriteEnumUsingToString, false);
		JSON.DEFAULT_GENERATE_FEATURE = SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.WriteEnumUsingName, false);
		JSON.DEFAULT_GENERATE_FEATURE = SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.DisableCircularReferenceDetect, true);
		TypeUtils.compatibleWithJavaBean = true;
		// ---fastjson config end---
		
		ConfigLoader.init("config.json");
		ConnectionsFilter.sessionCloseMessage = new TipPush(MessageConst.SERVER_CONNECTIONS_EXCEED);
		App.getApp().setDBSessionFactory(new SqlSessionFactory(new SqlSessionFactoryBuilder().build(IOUtils.getResource("mybatis.xml"))));
		TimeUpdater.getInstance(); // make it in the first pos of updater
		registerTemplates();
		launch();
		
//		runTest();
		App.getApp().addShutdownHook(new Runnable() {
			@Override
			public void run() {
				if (instance != null) {
					instance.running = false;
					instance = null;
				}
				App.getApp().getServiceManager().shutdown();
				IdUtils.close();
				App.getApp().getDBSessionFactory().close();
				LOG.info("[SERVER]SHUTDOWN OK");
			}
		});
		
		new Thread(new Server(), "SERVER-MAIN").start();
		WindowsShutdown.listen();
		LOG.info("[SERVER]START OK");
	}
	
	/**
	 * @throws Exception
	 */
	static void registerTemplates() throws Exception {
		TemplateService.register(ItemTemplate.class);
		TemplateService.register(DropGroupTemplate.class);
//		TemplateService.register(BuildTemplate.class);
//		TemplateService.register(BuildLevelUpTemplate.class);
//		TemplateService.register(BuildConditionTemplate.class);
		TemplateService.register(BuildTemplateV2.class);
		TemplateService.register(EmployeeProduceMoneyByQualityV2Template.class);
		TemplateService.register(LandTemplate.class);
		TemplateService.register(LandBuyTemplate.class);
		TemplateService.register(FinancialTemplate.class);
		TemplateService.register(PlayerLevelTemplate.class);
		TemplateService.register(ShopItemTemplate.class);
		TemplateService.register(PeakShopTemplate.class);
		TemplateService.register(TaskTemplate.class);
		TemplateService.register(AchievementTemplate.class);
		TemplateService.register(RechargeTemplate.class);
		TemplateService.register(BuffTemplate.class);
		TemplateService.register(WorldEventTemplate.class);
		TemplateService.register(WorldEventTimeTemplate.class);
//		TemplateService.register(TurnTableTemplate.class);
		TemplateService.register(AdventureTemplate.class);
		TemplateService.register(AdventureFixedProduceTemplate.class);
		TemplateService.register(TreasureBoxTemplate.class);
		TemplateService.register(DailyLoginRewardTemplate.class);
		TemplateService.register(MysteryShopItemTemplate.class);
		TemplateService.register(MysteryShopRefreshRuleTemplate.class);
		TemplateService.register(MysteryShopRefreshCostTemplate.class);
		TemplateService.register(SevenDaysSignInTemplate.class);
//		TemplateService.register(GiftExchangeTemplate.class);
		TemplateService.register(PetTemplate.class);
		TemplateService.register(PetSkillTemplate.class);
		TemplateService.register(PetSkillLevelUpTemplate.class);
		TemplateService.register(EmployeeTemplate.class);
//		TemplateService.register(EmployeeNameTemplate.class);
//		TemplateService.register(EmployeeProduceTemplate.class);
		TemplateService.register(SkillTemplate.class);
//		TemplateService.register(PlayerSkillLevelUpTemplate.class);
//		TemplateService.register(EmployeeIconTemplate.class);
//		TemplateService.register(EmployeeExpTemplate.class);
		TemplateService.register(EmployeeExpTemplateV2.class);
		TemplateService.register(EmployeeProduceV2Template.class);
//		TemplateService.register(EmployeeSkillProduceTemplate.class);
		TemplateService.register(EmployeeQualityUpStringTemplate.class);
		TemplateService.register(EmployeeQualityUpTemplate.class);
		TemplateService.register(EmployeeStarUpTemplate.class);
		TemplateService.register(EmployeeRecruitFixedDropTemplate.class);
		TemplateService.register(NpcTemplate.class);
		TemplateService.register(NpcTeamTemplate.class);
		TemplateService.register(StageAreaTemplate.class);
		TemplateService.register(StagePageTemplate.class);
		TemplateService.register(StageTemplate.class);
		TemplateService.register(DropItemToStageTemplate.class);
		TemplateService.register(ItemExchangeTemplate.class);
		TemplateService.register(VipTemplate.class);
		TemplateService.register(BigLuckDrawTemplate.class);
		TemplateService.register(EquipAttrWeightTemplate.class);
		TemplateService.register(EquipAttrNumWeightTemplate.class);
		TemplateService.register(EquipBaseTemplate.class);
		TemplateService.register(EquipDataTemplate.class);
		TemplateService.register(EquipSuitEffectTemplate.class);
//		TemplateService.register(ArenaScoreTemplate.class);
//		TemplateService.register(ArenaRewardTemplate.class);
		TemplateService.register(ArenaDailyRewardTemplate.class);
		TemplateService.register(RobotTemplate.class);
		TemplateService.register(Surprise7DaysTemplate.class);
		TemplateService.register(CircleRewardTemplate.class);
		TemplateService.register(CircleRankRewardTemplate.class);
		TemplateService.register(CircleShopTemplate.class);
		TemplateService.register(NewPlayerTaskTemplate.class);
		TemplateService.register(NewPlayerShopTemplate.class);
		TemplateService.register(NewPlayerViewTemplate.class);
		TemplateService.register(DestinyTemplate.class);
		TemplateService.register(GameStaticConfig.class);
		TemplateService.register(ResStageTypeTemplate.class);
		TemplateService.register(ResStageTemplate.class);
		TemplateService.register(PeakRoadTemplate.class);
		TemplateService.register(BuyCountTemplate.class);
		TemplateService.register(ThirtyDayRewardTemplate.class);
		TemplateService.register(ThirtyDayRechargeTemplate.class);
		TemplateService.register(ThirtyDayShopTemplate.class);
		TemplateService.register(CumulativeRechargeTemplate.class);
		TemplateService.register(EmployeeRecruiteShowTemplate.class);
		TemplateService.register(CombatAttributeTemplate.class);
		TemplateService.register(CombatPowerConfig.class);
		TemplateService.register(ClazzRestrainTemplate.class);
		TemplateService.register(CombatUtils.Config.class);
		TemplateService.register(MineTypeTemplate.class);
		TemplateService.register(EmployeeBlessTemplate.class);
		TemplateService.register(ArenaOpenTimeTemplate.class);
		TemplateService.register(QQShareActivityTemplate.class);
		TemplateService.register(GroupBuyTemplate.class);
		TemplateService.register(GroupBuyScoreRewardTemplate.class);
		TemplateService.register(GroupBuyConfig.class);
		TemplateService.register(SingleRechargeActivityTemplate.class);
		TemplateService.register(WorldBossConfig.class);
		TemplateService.register(WorldBossTemplate.class);
		TemplateService.register(WorldBossRankingRewardTemplate.class);
		TemplateService.register(GuildExpTemplate.class);
		TemplateService.register(GuildDonateTemplate.class);
	}
	
	static void launch() throws Exception {
		PlatformApi.init();
		IdUtils.init();
		
		App.getApp().getServiceManager().create(TemplateService.class);
		App.getApp().getServiceManager().create(AccountService.class);
		App.getApp().getServiceManager().create(PlayerService.class);
//		App.getApp().getServiceManager().create(ActorService.class);
		App.getApp().getServiceManager().create(PlayerCacheService.class);
		App.getApp().getServiceManager().create(PlatformGiftDispatchService.class);
		App.getApp().getServiceManager().create(ActivityService2.class);
		App.getApp().getServiceManager().create(VipService.class);
//		App.getApp().getServiceManager().create(WorldEventService.class);
//		App.getApp().getServiceManager().create(BuildService.class);
		App.getApp().getServiceManager().create(BuildServiceV2.class);
//		App.getApp().getServiceManager().create(LandService.class);
		App.getApp().getServiceManager().create(RelationService.class);
		App.getApp().getServiceManager().create(MailService.class);
		App.getApp().getServiceManager().create(TaskService.class);
		App.getApp().getServiceManager().create(FinancialService.class);
		App.getApp().getServiceManager().create(AchievementService.class);
		App.getApp().getServiceManager().create(RechargeService.class);
		App.getApp().getServiceManager().create(ItemService.class);
		App.getApp().getServiceManager().create(ShopService.class);
		App.getApp().getServiceManager().create(ChatService.class);
		App.getApp().getServiceManager().create(RankingService.class);
//		App.getApp().getServiceManager().create(TurnTableService.class);
		App.getApp().getServiceManager().create(ActivityNewPlayerService.class);//奇遇会loadactor 所以需要在奇遇前面 否则actor会有问题
		App.getApp().getServiceManager().create(GuildService.class);
		App.getApp().getServiceManager().create(TreasureBoxService.class);
		App.getApp().getServiceManager().create(DailyLoginActivityService.class);
		App.getApp().getServiceManager().create(MysteryShopService.class);
		App.getApp().getServiceManager().create(SevenDaysSignInActivityService.class);
		App.getApp().getServiceManager().create(DailyLimitBuyActivityService.class);
		App.getApp().getServiceManager().create(InviteActivityService.class);
		App.getApp().getServiceManager().create(GiftExchangeActivityService.class);
		App.getApp().getServiceManager().create(PetService.class);
		App.getApp().getServiceManager().create(EmployeeService.class);
		App.getApp().getServiceManager().create(PVEService.class);
		App.getApp().getServiceManager().create(ExchangeActivityService.class);
		App.getApp().getServiceManager().create(BuyCountService.class);
//		App.getApp().getServiceManager().create(OneYuanBigPrizeActivityService.class);
		App.getApp().getServiceManager().create(FirstRechargeService.class);
		App.getApp().getServiceManager().create(BigLuckDrawActivityService.class);
		App.getApp().getServiceManager().create(CharmTopActivityService.class);
		App.getApp().getServiceManager().create(CombatService.class);
		App.getApp().getServiceManager().create(FormationService.class);
		App.getApp().getServiceManager().create(ArenaService.class);
		App.getApp().getServiceManager().create(EquipmentService.class);
		App.getApp().getServiceManager().create(NewsService.class);
		App.getApp().getServiceManager().create(ConquestsService.class);
		App.getApp().getServiceManager().create(SkillService.class);
		App.getApp().getServiceManager().create(StrengthMealActivityService.class);
		App.getApp().getServiceManager().create(MapService.class);
		App.getApp().getServiceManager().create(AssistService.class);
		App.getApp().getServiceManager().create(ChipsCollectActivityService.class);
		App.getApp().getServiceManager().create(RedPacketActivityService.class);
		App.getApp().getServiceManager().create(MoonCardActivityService.class);
		App.getApp().getServiceManager().create(RechargeGiftActivityService.class);
		App.getApp().getServiceManager().create(Surprise7DaysActivityService.class);
//		App.getApp().getServiceManager().create(CircleActivityService.class);
		App.getApp().getServiceManager().create(PlayerTrainService.class);
		App.getApp().getServiceManager().create(ResStageService.class);
		App.getApp().getServiceManager().create(PeakRoadService.class);
		App.getApp().getServiceManager().create(ThirtyDaySignActivityService.class);
		App.getApp().getServiceManager().create(CumulativeRechargeActivityService.class);
		App.getApp().getServiceManager().create(VisitService.class);
		App.getApp().getServiceManager().create(AdventureService.class);
		App.getApp().getServiceManager().create(PartnerQQService.class);
		App.getApp().getServiceManager().create(WorldBossService.class);
		
		App.getApp().getServiceManager().create(HttpService.class);
//		if (App.getApp().getConfig().containsKey(Config.PROXY_PORT)) {
		if (App.getApp().getConfig().proxyPort != 0) {
			App.getApp().getServiceManager().create(ProxyClientSessionService.class);
		}
//		if (App.getApp().getConfig().containsKey(Config.WEBSOCKET_PORT)) {
		if (App.getApp().getConfig().port != 0) {
			App.getApp().getServiceManager().create(PomeloClientSessionService.class);
		}
		
//		App.getApp().getPacketDispatcher().addFilter(new ServerStateFilter());
		App.getApp().getPacketDispatcher().addFilter(new PlayerFilter());
	}
	
	@Override
	public void run() {
		while (running) {
			long millis = TimeUpdater.getInstance().utc();
			try {
				App.getApp().getUpdater().update();
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
			millis = TimeUpdater.getInstance().utc() - millis;
			if (millis > 100) {
				LOG.warn("[SERVER]UPDATE TOO LONG[" + millis + "]");
			}
			long t = DEFAULT_UPDATE_TIME - millis;
			if (t > 0) {
				try {
					Thread.sleep(t);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static Server getInstance() {
		return instance;
	}
	
	public static void broadcast(Packet... packets) {
		ClientSessionService service = App.getApp().getServiceManager().get(ProxyClientSessionService.class);
		broadcast(service, packets);
		service = App.getApp().getServiceManager().get(PomeloClientSessionService.class);
		broadcast(service, packets);
	}
	
	private static void broadcast(ClientSessionService service, Packet...packets) {
		if (service != null) {
			for (Packet packet : packets) {
				service.broadcast(packet);
			}
		}
	}
	
	public static String makeSign(Map<String, String> map) {
		Map<String, String> tree = map instanceof TreeMap ? map : new TreeMap<String, String>(map);
		StringBuilder buf = new StringBuilder(128);
		for (Entry<String, String> entry : tree.entrySet()) {
			buf.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
		}
//		buf.append("key=").append(App.getApp().getConfig().getString(Config.SECRET_KEY));
		buf.append("key=").append(App.getApp().getConfig().secretKey);
		return CommonUtils.md5(buf.toString());
	}
	
	public boolean hasState(int mask) {
		return (state & mask) != 0;
	}

}
